package cn.itcast.erp.filter;


import cn.itcast.erp.dao.mapper.MenuMapper;
import cn.itcast.erp.entity.Emp;
import cn.itcast.erp.entity.Menu;
import cn.itcast.erp.service.MenuService;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class LoginFilter implements Filter {



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化, 当前的过滤器对象创建出来的时候, 该方法会执行
        // 一般在该方法中读取web.xml中的参数
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 过滤器,过滤html
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();

        // 从session中取出登录的用户信息
        Emp emp = (Emp)session.getAttribute("emp");
        // 如果可以取出用户
        if (emp != null || req.getRequestURI().equals("/login.html")) {
            chain.doFilter(request, response);
        }
        else {

            // 用户没登录
            HttpServletResponse resp = (HttpServletResponse) response;
            // 重定向回登录页面
            resp.sendRedirect("/login.html");
        }
    }


    @Override
    public void destroy() {
        // 当前过滤器被销毁的时候会执行
        // 一般用于释放资源
    }




}
